<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>购物车</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@3.2.38/dist/vue.global.min.js"></script>
  <style>
    table {
      border-collapse: collapse;
    }

    th,
    td {
      width: 80px;
      padding: 6px;
      text-align: center;

    }

    input {
      width: 80px;
    }
  </style>
</head>

<body>
  <div id="app">
    <button @click="showAddBtn">添加</button>

    <table border>
      <tr>
        <th>id</th>
        <th>商品名称</th>
        <th>商品价格</th>
        <th>商品数量</th>
        <th>操作</th>
      </tr>

      <template v-for="(item,index) in dataList" :key="item.id">
        <tr>
          <td>{{item.id}}</td>
          <td>{{item.name}}</td>
          <td>{{item.price}}</td>
          <td>
            <button :disabled="item.num >0 ? false : true" @click="sub(index)">-</button>
            {{item.num}}
            <button @click="add(index)">+</button></button>
          </td>
          <td><button @click="remove(index)">移除</button></td>
        </tr>
      </template>
      <tr v-if="showAdd">
        <td><input type="text" v-model="newGoods.id"></td>
        <td><input type="text" v-model="newGoods.name"></td>
        <td><input type="number" v-model="newGoods.price"></td>
        <td><input type="number" v-model="newGoods.num"></td>
        <td><button @click="increase">确定</button></td>
      </tr>
    </table>
    <h1>总价格：￥{{allPrice.toFixed(2)}}</h1>
  </div>
</body>
<script>
  Vue.createApp({
    computed: {
      allPrice() {
        let sum = 0
        for (let i = 0; i < this.dataList.length; i++) {
          sum += this.dataList[i].price * this.dataList[i].num
        }
        return sum
      }
    },
    data() {
      return {
        showAdd: false,
        dataList: [{
          id: 1,
          name: '充电宝',
          price: '99.111',
          num: 1,
        }, {
          id: 2,
          name: '小风扇',
          price: '88.222',
          num: 1,
        }, {
          id: 3,
          name: '小音箱',
          price: '125.533',
          num: 1,
        }, {
          id: 4,
          name: '蓝牙耳机',
          price: '315.544',
          num: 1,
        }],
        newGoods: {
          id: '',
          name: '',
          price: '',
          num: '',
        }
      }
    },
    methods: {
      sub(index) {
        this.dataList[index].num--
      },
      add(index) {
        this.dataList[index].num++
      },
      showAddBtn(index) {
        this.showAdd = !this.showAdd
      },
      remove(index) {
        this.dataList.splice(index, 1)
      },
      increase() {
        this.dataList.push(this.newGoods)
        this.newGoods = {}
      }
    },
  }).mount('#app')
</script>

</html>